package com.hqq.helper;

import com.hqq.annotation.Action;
import com.hqq.http.Handler;
import com.hqq.http.Request;
import com.hqq.http.RequestMethod;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * ControllerHelper
 * Controller帮助类
 * 用于存放请求的路径和方法，根据路径获取方法
 * Created by heqianqian on 2017/7/19.
 */
public class ControllerHelper {

    private static final Map<Request, Handler> ACTION_MAP;

    static {
        ACTION_MAP = new HashMap<>();
        Set<Class<?>> controllerClasses = ClassHelper.getControllerClasses();
        if (CollectionUtils.isNotEmpty(controllerClasses)) {
            for (Class controllerClass : controllerClasses) {//遍历Controller类
                Method[] controllerMethods = controllerClass.getDeclaredMethods();
                if (ArrayUtils.isNotEmpty(controllerMethods)) {//遍历Controller中的方法
                    for (Method method : controllerMethods) {
                        if (method.isAnnotationPresent(Action.class)) {//如果方法被注解修饰
                            Action action = method.getAnnotation(Action.class);
                            String requestPath = action.value();
                            RequestMethod requestMethod = action.method();
                            Request request = new Request(requestMethod, requestPath);
                            Handler handler = new Handler(controllerClass, method);
                            ACTION_MAP.put(request, handler);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取Action信息
     *
     * @param requestMethod 请求方法
     * @param requestPath   请求路径
     * @return Handler
     */
    public static Handler getHandler(RequestMethod requestMethod, String requestPath) {
        Request request = new Request(requestMethod, requestPath);
        return ACTION_MAP.get(request);
    }

    public static Map<Request, Handler> getActionMap() {
        return ACTION_MAP;
    }
}
